package com.ruoyi.admin.controller;

import java.util.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.admin.service.ICreditRecordService;
import com.ruoyi.admin.service.IEventApplyService;
import com.ruoyi.admin.service.IEventDetailService;
import com.ruoyi.admin.service.IRewardExchangeService;
import com.ruoyi.admin.service.IRewardService;
import com.ruoyi.admin.service.IUserTService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.CreditRecord;
import com.ruoyi.common.core.domain.entity.EventApply;
import com.ruoyi.common.core.domain.entity.EventDetail;
import com.ruoyi.common.core.domain.entity.Reward;
import com.ruoyi.common.core.domain.entity.RewardExchange;
import com.ruoyi.admin.domain.RewardExchangeVO;
import com.ruoyi.common.utils.EventStatusUtils;


/**
 * 首页数据 控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dashboard")
public class DashboardController extends BaseController
{
    @Autowired
    private IEventDetailService eventDetailService;
    
    @Autowired
    private IEventApplyService eventApplyService;
    
    @Autowired
    private ICreditRecordService creditRecordService;
    
    @Autowired
    private IRewardExchangeService rewardExchangeService;
    
    @Autowired
    private IRewardService rewardService;
    
    @Autowired
    private IUserTService userTService;
    
    /**
     * 获取首页统计数据
     */
    @PreAuthorize("@ss.hasPermi('system:dashboard:list')")
    @GetMapping("/data")
    public AjaxResult getDashboardData()
    {
        Map<String, Object> data = new HashMap<>();
        
        // 统计活动总数
        EventDetail eventDetail = new EventDetail();
        List<EventDetail> eventList = eventDetailService.selectEventDetailList(eventDetail);
        int totalActivities = eventList.size();
        
        // 统计参与人数
        EventApply eventApply = new EventApply();
        List<EventApply> applyList = eventApplyService.selectEventApplyList(eventApply);
        int totalParticipants = applyList.size();
        
        // 统计积分发放总量
        CreditRecord creditRecord = new CreditRecord();
        List<CreditRecord> creditList = creditRecordService.selectCreditRecordList(creditRecord);
        int totalCredits = 0;
        for (CreditRecord record : creditList) {
            if (record.getCredit() != null) {
                totalCredits += record.getCredit();
            }
        }
        
        // 统计兑换次数
        RewardExchange rewardExchange = new RewardExchange();
        List<RewardExchangeVO> exchangeList = rewardExchangeService.selectRewardExchangeList(rewardExchange);
        int totalExchanges = exchangeList.size();
        
        data.put("totalActivities", totalActivities);
        data.put("totalParticipants", totalParticipants);
        data.put("totalCredits", totalCredits);
        data.put("totalExchanges", totalExchanges);
        
        return AjaxResult.success(data);
    }
    
    /**
     * 获取活动趋势数据
     */
    @PreAuthorize("@ss.hasPermi('system:dashboard:list')")
    @GetMapping("/activityTrend")
    public AjaxResult getActivityTrend(@RequestParam(required = false, defaultValue = "month") String timeRange)
    {
        Map<String, Object> data = new HashMap<>();
        List<String> timeLabels = new ArrayList<>();
        List<Integer> activities = new ArrayList<>();
        List<Integer> participants = new ArrayList<>();
        
        // 获取所有活动和报名数据
        EventDetail eventDetailQuery = new EventDetail();
        List<EventDetail> allEvents = eventDetailService.selectEventDetailList(eventDetailQuery);
        
        EventApply eventApplyQuery = new EventApply();
        List<EventApply> allApplies = eventApplyService.selectEventApplyList(eventApplyQuery);
        
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter;
        
        // 根据时间范围生成不同的数据
        switch (timeRange) {
            case "day":
                formatter = DateTimeFormatter.ofPattern("HH:00");
                // 生成24小时的标签
                for (int i = 0; i < 24; i++) {
                    String hour = String.format("%02d:00", i);
                    timeLabels.add(hour);
                    
                    // 统计当天每小时的活动数和参与人数
                    int hourlyActivities = 0;
                    int hourlyParticipants = 0;
                    
                    for (EventDetail event : allEvents) {
                        if (event.getEventBegin() != null && 
                            event.getEventBegin().equals(now) &&
                            event.getEventBegin().getHours() == i) {
                            hourlyActivities++;
                        }
                    }
                    
                    for (EventApply apply : allApplies) {
                        if (apply.getApplyTime() != null && 
                            apply.getApplyTime().equals(now) &&
                            apply.getApplyTime().getHours() == i) {
                            hourlyParticipants++;
                        }
                    }
                    
                    activities.add(hourlyActivities);
                    participants.add(hourlyParticipants);
                }
                break;
                
            case "week":
                formatter = DateTimeFormatter.ofPattern("E");
                String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
                LocalDate startOfWeek = now.minusDays(now.getDayOfWeek().getValue() - 1);
                
                for (int i = 0; i < 7; i++) {
                    LocalDate day = startOfWeek.plusDays(i);
                    timeLabels.add(weekDays[i]);
                    
                    // 统计本周每天的活动数和参与人数
                    int dailyActivities = 0;
                    int dailyParticipants = 0;
                    
                    for (EventDetail event : allEvents) {
                        if (event.getEventBegin() != null && 
                            event.getEventBegin().equals(day)) {
                            dailyActivities++;
                        }
                    }
                    
                    for (EventApply apply : allApplies) {
                        if (apply.getApplyTime() != null && 
                            apply.getApplyTime().equals(day)) {
                            dailyParticipants++;
                        }
                    }
                    
                    activities.add(dailyActivities);
                    participants.add(dailyParticipants);
                }
                break;
                
            case "year":
                formatter = DateTimeFormatter.ofPattern("M月");
                for (int i = 1; i <= 12; i++) {
                    LocalDate month = LocalDate.of(now.getYear(), i, 1);
                    timeLabels.add(i + "月");
                    
                    // 统计本年每月的活动数和参与人数
                    int monthlyActivities = 0;
                    int monthlyParticipants = 0;
                    
                    for (EventDetail event : allEvents) {
                        if (event.getEventBegin() != null && 
                            event.getEventBegin().getYear() == now.getYear() &&
                            event.getEventBegin().getMonth() == i) {
                            monthlyActivities++;
                        }
                    }
                    
                    for (EventApply apply : allApplies) {
                        if (apply.getApplyTime() != null && 
                            apply.getApplyTime().getYear() == now.getYear() &&
                            apply.getApplyTime().getMonth() == i) {
                            monthlyParticipants++;
                        }
                    }
                    
                    activities.add(monthlyActivities);
                    participants.add(monthlyParticipants);
                }
                break;
                
            case "month":
            default:
                formatter = DateTimeFormatter.ofPattern("d日");
                LocalDate startOfMonth = now.withDayOfMonth(1);
                int daysInMonth = now.lengthOfMonth();
                
                for (int i = 1; i <= daysInMonth; i++) {
                    LocalDate day = LocalDate.of(now.getYear(), now.getMonth(), i);
                    timeLabels.add(i + "日");
                    
                    // 统计本月每天的活动数和参与人数
                    int dailyActivities = 0;
                    int dailyParticipants = 0;
                    
                    for (EventDetail event : allEvents) {
                        if (event.getEventBegin() != null && 
                            event.getEventBegin().getYear() == now.getYear() &&
                            event.getEventBegin().getMonth() == now.getMonthValue()
//                                && event.getEventBegin().toLocalDateTime().getDayOfMonth() == i
                        ) {
                            dailyActivities++;
                        }
                    }
                    
                    for (EventApply apply : allApplies) {
                        if (apply.getApplyTime() != null && 
                            apply.getApplyTime().getYear() == now.getYear() &&
                            apply.getApplyTime().getMonth() == now.getMonthValue()
//                                && apply.getApplyTime().getDayOfMonth() == i
                        ) {
                            dailyParticipants++;
                        }
                    }
                    
                    activities.add(dailyActivities);
                    participants.add(dailyParticipants);
                }
                break;
        }
        
        data.put("timeLabels", timeLabels);
        data.put("activities", activities);
        data.put("participants", participants);
        
        return AjaxResult.success(data);
    }
    
    /**
     * 获取热门活动排行
     */
    @PreAuthorize("@ss.hasPermi('system:dashboard:list')")
    @GetMapping("/hotActivities")
    public AjaxResult getHotActivities()
    {
        List<Map<String, Object>> hotActivities = new ArrayList<>();
        
        // 获取所有活动
        EventDetail eventDetailQuery = new EventDetail();
        List<EventDetail> allEvents = eventDetailService.selectEventDetailList(eventDetailQuery);
        
        // 获取所有报名记录
        EventApply eventApplyQuery = new EventApply();
        List<EventApply> allApplies = eventApplyService.selectEventApplyList(eventApplyQuery);
        
        // 统计每个活动的报名人数
        Map<Long, Integer> eventParticipantsCount = new HashMap<>();
        Map<Long, EventDetail> eventMap = new HashMap<>();
        
        for (EventDetail event : allEvents) {
            eventMap.put(event.getId(), event);
            eventParticipantsCount.put(event.getId(), 0);
        }
        
        for (EventApply apply : allApplies) {
            Long eventId = apply.getEventId();
            if (eventParticipantsCount.containsKey(eventId)) {
                eventParticipantsCount.put(eventId, eventParticipantsCount.get(eventId) + 1);
            }
        }
        
        // 按报名人数排序
        List<Map.Entry<Long, Integer>> sortedEvents = new ArrayList<>(eventParticipantsCount.entrySet());
        sortedEvents.sort(Map.Entry.<Long, Integer>comparingByValue().reversed());
        
        // 取前5个活动
        int count = 0;
        for (Map.Entry<Long, Integer> entry : sortedEvents) {
            if (count >= 5) break;
            
            Long eventId = entry.getKey();
            Integer participants = entry.getValue();
            EventDetail event = eventMap.get(eventId);
            
            if (event != null) {
                Map<String, Object> activityData = new HashMap<>();
                activityData.put("name", event.getTitle());
                
                // 判断活动状态
                String status = EventStatusUtils.getEventStatusInfo(event);
                
                activityData.put("status", status);
                activityData.put("participants", participants);
                
                hotActivities.add(activityData);
                count++;
            }
        }
        
        return AjaxResult.success(hotActivities);
    }
    
    /**
     * 获取积分兑换情况
     */
    @PreAuthorize("@ss.hasPermi('system:dashboard:list')")
    @GetMapping("/exchangeStats")
    public AjaxResult getExchangeStats()
    {
        List<Map<String, Object>> exchangeStats = new ArrayList<>();
        
        // 获取所有奖品
        Reward rewardQuery = new Reward();
        List<Reward> allRewards = rewardService.selectRewardList(rewardQuery);
        
        // 获取所有兑换记录
        RewardExchange exchangeQuery = new RewardExchange();
        List<RewardExchangeVO> allExchanges = rewardExchangeService.selectRewardExchangeList(exchangeQuery);
        
        // 统计每种奖品的兑换次数
        Map<Long, Integer> rewardExchangeCount = new HashMap<>();
        Map<Long, String> rewardNameMap = new HashMap<>();
        
        for (Reward reward : allRewards) {
            rewardExchangeCount.put(reward.getId(), 0);
            rewardNameMap.put(reward.getId(), reward.getTitle());
        }
        
        for (RewardExchangeVO exchange : allExchanges) {
            Long rewardId = exchange.getRewardId();
            if (rewardExchangeCount.containsKey(rewardId)) {
                rewardExchangeCount.put(rewardId, (int) (rewardExchangeCount.get(rewardId) + exchange.getAmount()));
            }
        }
        
        // 按兑换次数排序
        List<Map.Entry<Long, Integer>> sortedRewards = new ArrayList<>(rewardExchangeCount.entrySet());
        sortedRewards.sort(Map.Entry.<Long, Integer>comparingByValue().reversed());
        
        // 取前5个奖品
        int count = 0;
        for (Map.Entry<Long, Integer> entry : sortedRewards) {
            if (count >= 5) break;
            
            Long rewardId = entry.getKey();
            Integer exchangeCount = entry.getValue();
            String rewardName = rewardNameMap.get(rewardId);
            
            if (rewardName != null && exchangeCount > 0) {
                Map<String, Object> exchangeData = new HashMap<>();
                exchangeData.put("name", rewardName);
                exchangeData.put("count", exchangeCount);
                
                exchangeStats.add(exchangeData);
                count++;
            }
        }
        
        return AjaxResult.success(exchangeStats);
    }
} 